package com.ruoyi.functiontest.controller;

import java.util.List;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.functiontest.domain.InterchangeStatTest;
import com.ruoyi.functiontest.service.IInterchangeStatTestService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 枢纽互通统计测试Controller
 * 
 * @author ruoyi
 * @date 2025-09-25
 */
@RestController
@RequestMapping("/functiontest/InterchangeStatTest")
public class InterchangeStatTestController extends BaseController
{
    @Autowired
    private IInterchangeStatTestService interchangeStatTestService;

    /**
     * 查询枢纽互通统计测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:list')")
    @GetMapping("/list")
    public AjaxResult list(InterchangeStatTest interchangeStatTest)
    {
        List<InterchangeStatTest> list = interchangeStatTestService.selectInterchangeStatTestList(interchangeStatTest);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = interchangeStatTest.getRoadName() != null && !interchangeStatTest.getRoadName().isEmpty() ||
                                   interchangeStatTest.getNodeName() != null && !interchangeStatTest.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<InterchangeStatTest> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出枢纽互通统计测试列表
     * 按照树形结构的层次顺序导出所有节点，包括所有子树
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:export')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InterchangeStatTest interchangeStatTest)
    {
        // 按照树形结构的层次顺序导出所有节点，包括所有子树
        List<InterchangeStatTest> list = interchangeStatTestService.selectInterchangeStatTestList(interchangeStatTest);
        
        // 构建树形结构
        List<InterchangeStatTest> treeList = buildTree(list);
        
        // 将树形结构按照层次顺序展平为列表
        List<InterchangeStatTest> exportList = new ArrayList<>();
        flattenTree(treeList, exportList);
        
        ExcelUtil<InterchangeStatTest> util = new ExcelUtil<InterchangeStatTest>(InterchangeStatTest.class);
        util.exportExcel(response, exportList, "枢纽互通统计测试数据");
    }

    /**
     * 导入枢纽互通统计测试数据
     * 简化导入逻辑：直接按照Excel原始格式导入，通过id和parentid来确定数据
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:import')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<InterchangeStatTest> util = new ExcelUtil<InterchangeStatTest>(InterchangeStatTest.class);
        List<InterchangeStatTest> importList = util.importExcel(file.getInputStream());
        
        // 简化导入逻辑：直接按照Excel原始格式导入，通过id和parentid来确定数据
        String message = interchangeStatTestService.importInterchangeStatTest(importList, updateSupport);
        return success(message);
    }

    /**
     * 导入模板下载
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:import')")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        List<InterchangeStatTest> templateList = new ArrayList<>();
        
        // 六安根节点
        InterchangeStatTest liuanRoot = new InterchangeStatTest();
        liuanRoot.setId(1L);
        liuanRoot.setParentId(0L);
        liuanRoot.setRoadName("六安");
        liuanRoot.setNodeName("");
        liuanRoot.setMainLength(new BigDecimal("0"));
        liuanRoot.setRampAvgLength(new BigDecimal("0"));
        liuanRoot.setTollCenterLength(new BigDecimal("0"));
        liuanRoot.setApproachAvgLength(new BigDecimal("0"));
        templateList.add(liuanRoot);
        
        // 六安子节点
        InterchangeStatTest tongyun = new InterchangeStatTest();
        tongyun.setId(2L);
        tongyun.setParentId(1L);
        tongyun.setRoadName("");
        tongyun.setNodeName("同云枢纽互通");
        tongyun.setMainLength(new BigDecimal("0"));
        tongyun.setRampAvgLength(new BigDecimal("1420.03"));
        tongyun.setTollCenterLength(new BigDecimal("0"));
        tongyun.setApproachAvgLength(new BigDecimal("0"));
        templateList.add(tongyun);
        
        InterchangeStatTest dingyun = new InterchangeStatTest();
        dingyun.setId(3L);
        dingyun.setParentId(1L);
        dingyun.setRoadName("");
        dingyun.setNodeName("顶云枢纽互通");
        dingyun.setMainLength(new BigDecimal("1030.56"));
        dingyun.setRampAvgLength(new BigDecimal("2439.23"));
        dingyun.setTollCenterLength(new BigDecimal("0"));
        dingyun.setApproachAvgLength(new BigDecimal("0"));
        templateList.add(dingyun);
        
        InterchangeStatTest zhenfeng = new InterchangeStatTest();
        zhenfeng.setId(4L);
        zhenfeng.setParentId(1L);
        zhenfeng.setRoadName("");
        zhenfeng.setNodeName("贞丰枢纽互通");
        zhenfeng.setMainLength(new BigDecimal("927.51"));
        zhenfeng.setRampAvgLength(new BigDecimal("1888.19"));
        zhenfeng.setTollCenterLength(new BigDecimal("0"));
        zhenfeng.setApproachAvgLength(new BigDecimal("0"));
        templateList.add(zhenfeng);
        
        InterchangeStatTest muzan = new InterchangeStatTest();
        muzan.setId(5L);
        muzan.setParentId(1L);
        muzan.setRoadName("");
        muzan.setNodeName("木咱枢纽互通");
        muzan.setMainLength(new BigDecimal("0"));
        muzan.setRampAvgLength(new BigDecimal("1032.42"));
        muzan.setTollCenterLength(new BigDecimal("0"));
        muzan.setApproachAvgLength(new BigDecimal("0"));
        templateList.add(muzan);
        
        // 纳晴根节点
        InterchangeStatTest naqingRoot = new InterchangeStatTest();
        naqingRoot.setId(6L);
        naqingRoot.setParentId(0L);
        naqingRoot.setRoadName("纳晴");
        naqingRoot.setNodeName("");
        naqingRoot.setMainLength(new BigDecimal("0"));
        naqingRoot.setRampAvgLength(new BigDecimal("0"));
        naqingRoot.setTollCenterLength(new BigDecimal("0"));
        naqingRoot.setApproachAvgLength(new BigDecimal("0"));
        templateList.add(naqingRoot);
        
        // 纳晴子节点
        InterchangeStatTest zangkejiangbei = new InterchangeStatTest();
        zangkejiangbei.setId(8L);
        zangkejiangbei.setParentId(6L);
        zangkejiangbei.setRoadName("");
        zangkejiangbei.setNodeName("牂牁江北收费站互通");
        zangkejiangbei.setMainLength(new BigDecimal("1110.83"));
        zangkejiangbei.setRampAvgLength(new BigDecimal("1010.64"));
        zangkejiangbei.setTollCenterLength(new BigDecimal("1131.41"));
        zangkejiangbei.setApproachAvgLength(new BigDecimal("2501.65"));
        templateList.add(zangkejiangbei);
        
        InterchangeStatTest huangtian = new InterchangeStatTest();
        huangtian.setId(9L);
        huangtian.setParentId(6L);
        huangtian.setRoadName("");
        huangtian.setNodeName("荒田枢纽互通");
        huangtian.setMainLength(new BigDecimal("1100.20"));
        huangtian.setRampAvgLength(new BigDecimal("1754.89"));
        huangtian.setTollCenterLength(new BigDecimal("0"));
        huangtian.setApproachAvgLength(new BigDecimal("0"));
        templateList.add(huangtian);
        
        InterchangeStatTest changliu = new InterchangeStatTest();
        changliu.setId(10L);
        changliu.setParentId(6L);
        changliu.setRoadName("");
        changliu.setNodeName("长流收费站互通");
        changliu.setMainLength(new BigDecimal("1062.41"));
        changliu.setRampAvgLength(new BigDecimal("921.90"));
        changliu.setTollCenterLength(new BigDecimal("658.63"));
        changliu.setApproachAvgLength(new BigDecimal("4554.23"));
        templateList.add(changliu);
        
        InterchangeStatTest zhaile = new InterchangeStatTest();
        zhaile.setId(11L);
        zhaile.setParentId(6L);
        zhaile.setRoadName("");
        zhaile.setNodeName("寨乐枢纽互通");
        zhaile.setMainLength(new BigDecimal("1171.58"));
        zhaile.setRampAvgLength(new BigDecimal("1272.99"));
        zhaile.setTollCenterLength(new BigDecimal("0"));
        zhaile.setApproachAvgLength(new BigDecimal("0"));
        templateList.add(zhaile);
        
        InterchangeStatTest zhongying = new InterchangeStatTest();
        zhongying.setId(12L);
        zhongying.setParentId(6L);
        zhongying.setRoadName("");
        zhongying.setNodeName("中营收费站互通");
        zhongying.setMainLength(new BigDecimal("1076.98"));
        zhongying.setRampAvgLength(new BigDecimal("846.68"));
        zhongying.setTollCenterLength(new BigDecimal("115.46"));
        zhongying.setApproachAvgLength(new BigDecimal("261.11"));
        templateList.add(zhongying);
        
        InterchangeStatTest nayongxi = new InterchangeStatTest();
        nayongxi.setId(13L);
        nayongxi.setParentId(6L);
        nayongxi.setRoadName("");
        nayongxi.setNodeName("纳雍西收费站互通");
        nayongxi.setMainLength(new BigDecimal("1130.62"));
        nayongxi.setRampAvgLength(new BigDecimal("894.98"));
        nayongxi.setTollCenterLength(new BigDecimal("333.28"));
        nayongxi.setApproachAvgLength(new BigDecimal("830.69"));
        templateList.add(nayongxi);
        
        InterchangeStatTest huagong = new InterchangeStatTest();
        huagong.setId(14L);
        huagong.setParentId(6L);
        huagong.setRoadName("");
        huagong.setNodeName("花贡收费站互通");
        huagong.setMainLength(new BigDecimal("1237.92"));
        huagong.setRampAvgLength(new BigDecimal("933.92"));
        huagong.setTollCenterLength(new BigDecimal("201.78"));
        huagong.setApproachAvgLength(new BigDecimal("610.01"));
        templateList.add(huagong);
        
        InterchangeStatTest zhangwei = new InterchangeStatTest();
        zhangwei.setId(15L);
        zhangwei.setParentId(6L);
        zhangwei.setRoadName("");
        zhangwei.setNodeName("张维收费站互通");
        zhangwei.setMainLength(new BigDecimal("1172.73"));
        zhangwei.setRampAvgLength(new BigDecimal("868.40"));
        zhangwei.setTollCenterLength(new BigDecimal("154.39"));
        zhangwei.setApproachAvgLength(new BigDecimal("575.92"));
        templateList.add(zhangwei);
        
        ExcelUtil<InterchangeStatTest> util = new ExcelUtil<InterchangeStatTest>(InterchangeStatTest.class);
        util.exportExcel(response, templateList, "枢纽互通统计测试导入模板");
    }

    /**
     * 构建树形结构
     */
    private List<InterchangeStatTest> buildTree(List<InterchangeStatTest> list) {
        // 构建父子关系映射
        Map<Long, InterchangeStatTest> nodeMap = new HashMap<>();
        List<InterchangeStatTest> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (InterchangeStatTest node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (InterchangeStatTest node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                InterchangeStatTest parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<InterchangeStatTest>());
                    }
                    @SuppressWarnings("unchecked")
                    List<InterchangeStatTest> children = (List<InterchangeStatTest>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }

    /**
     * 将树形结构按照层次顺序展平为列表
     */
    private void flattenTree(List<InterchangeStatTest> treeList, List<InterchangeStatTest> resultList) {
        for (InterchangeStatTest node : treeList) {
            // 添加当前节点到结果列表
            resultList.add(node);
            
            // 递归处理子节点
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                @SuppressWarnings("unchecked")
                List<InterchangeStatTest> children = (List<InterchangeStatTest>) node.getChildren();
                flattenTree(children, resultList);
            }
        }
    }

    /**
     * 获取枢纽互通统计测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(interchangeStatTestService.selectInterchangeStatTestById(id));
    }

    /**
     * 新增枢纽互通统计测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:add')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InterchangeStatTest interchangeStatTest)
    {
        return toAjax(interchangeStatTestService.insertInterchangeStatTest(interchangeStatTest));
    }

    /**
     * 修改枢纽互通统计测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:edit')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InterchangeStatTest interchangeStatTest)
    {
        return toAjax(interchangeStatTestService.updateInterchangeStatTest(interchangeStatTest));
    }

    /**
     * 删除枢纽互通统计测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:remove')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否可以删除节点（父节点必须在子节点删除完后才能删除）
        for (Long id : ids) {
            if (interchangeStatTestService.hasChildById(id)) {
                return error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        
        return toAjax(interchangeStatTestService.deleteInterchangeStatTestByIds(ids));
    }
    
    /**
     * 实测单位批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:fieldAudit')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/fieldAudit/batch")
    public AjaxResult fieldAuditBatch()
    {
        try {
            // 批量更新所有记录的review1字段为0
            int updatedCount = interchangeStatTestService.updateReview1ToZero();
            System.out.println("实测单位批量审核完成，更新记录数：" + updatedCount);
            return success("实测单位批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("实测单位批量审核失败：" + e.getMessage());
            return error("实测单位批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 业主批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:ownerAudit')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/ownerAudit/batch")
    public AjaxResult ownerAuditBatch(@RequestBody Map<String, Object> params)
    {
        try {
            Long deptId = params.get("deptId") != null ? Long.valueOf(params.get("deptId").toString()) : null;
            Long roleId = params.get("roleId") != null ? Long.valueOf(params.get("roleId").toString()) : null;
            
            System.out.println("业主批量审核 - 审核所有数据，deptId: " + deptId + ", roleId: " + roleId);
            
            // 1. 校验所有数据的review1字段是否都为0
            boolean allReview1Zero = interchangeStatTestService.checkAllReview1IsZero();
            if (!allReview1Zero) {
                return error("业主批量审核失败：存在未通过实测单位审核的数据，请先完成实测单位审核");
            }
            
            // 2. 构建查询条件
            InterchangeStatTest queryCondition = new InterchangeStatTest();
            queryCondition.setDeptId(deptId);
            queryCondition.setRoleId(roleId);
            
            // 3. 从params中提取查询条件
            if (params.get("roadName") != null) {
                queryCondition.setRoadName(params.get("roadName").toString());
            }
            if (params.get("nodeName") != null) {
                queryCondition.setNodeName(params.get("nodeName").toString());
            }
            
            // 4. 根据条件批量更新业主审核状态
            int updatedCount = interchangeStatTestService.updateReview2ToZeroByCondition(queryCondition);
            
            System.out.println("业主批量审核完成，更新记录数：" + updatedCount);
            return success("业主批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("业主批量审核失败：" + e.getMessage());
            return error("业主批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 中心批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:centerAudit')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/centerAudit/batch")
    public AjaxResult centerAuditBatch()
    {
        try {
            System.out.println("中心批量审核 - 审核所有数据");
            
            // 1. 校验所有数据的review1和review2字段是否都不为空且都为0
            boolean allReview1AndReview2Zero = interchangeStatTestService.checkAllReview1AndReview2AreZero();
            if (!allReview1AndReview2Zero) {
                return error("中心批量审核失败：存在未通过实测单位审核或业主审核的数据，请先完成前序审核");
            }
            
            // 2. 批量更新中心审核状态
            int updatedCount = interchangeStatTestService.updateReview3ToZero();
            
            System.out.println("中心批量审核完成，更新记录数：" + updatedCount);
            return success("中心批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("中心批量审核失败：" + e.getMessage());
            return error("中心批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 同步数据到正式表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:InterchangeStatTest:syncToInterchangeStat')")
    @Log(title = "枢纽互通统计测试", businessType = BusinessType.UPDATE)
    @PostMapping("/syncToInterchangeStat")
    public AjaxResult syncToInterchangeStat()
    {
        try {
            System.out.println("开始同步数据到正式表");
            
            String result = interchangeStatTestService.syncDataToInterchangeStat();
            
            System.out.println("数据同步完成：" + result);
            return success(result);
        } catch (Exception e) {
            System.err.println("数据同步失败：" + e.getMessage());
            return error("数据同步失败：" + e.getMessage());
        }
    }
}
